package Plugins::SBDir2Lib::Plugin;

#	----------------------------------------------------------------------
#	S B D i r 2 L i b 
#	----------------------------------------------------------------------
#
#	Author:	Guenther Roll <guenther.roll(at)gmail(dot)com>
#
#	Copyright (c) 2015 Guenther Roll
#	All rights reserved.
#
#	----------------------------------------------------------------------
#
# 	This program is free software; you can redistribute it and/or
# 	modify it under the terms of the GNU General Public License,
# 	version 2.
#
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#
#	You should have received a copy of the GNU General Public License
#	along with this program; if not, write to the Free Software
#	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
#	02111-1307 USA
#
#	----------------------------------------------------------------------


use strict;

use base qw(Slim::Plugin::Base);

use Slim::Menu::BrowseLibrary;
use Slim::Music::Import;
use Slim::Utils::Log;
use Slim::Utils::Prefs;

use Plugins::SBDir2Lib::ConfigParser;
use Plugins::SBDir2Lib::Settings;


#----------------------------------------------------------------------
my $prefs    = preferences('plugin.SBDir2Lib'); 	#name of preferences file: prefs\plugin\SBDir2Lib.pref
my $srvprefs = preferences('server');
my $ConfigParser = undef;

#----------------------------------------------------------------------
my $log = Slim::Utils::Log->addLogCategory({
	'category'     => 'plugin.SBDir2Lib',
	'defaultLevel' => 'ERROR',
	'description'  => 'PLUGIN_SBDIR2LIB',
});

#----------------------------------------------------------------------
sub initPlugin {
	my $class = shift;

	# Initialize settings class
	if ( main::WEBUI ) {
		require Plugins::SBDir2Lib::Settings;
		my $classSettings = Plugins::SBDir2Lib::Settings->new($class);
	}

	my $ConfigParser = GetConfigParser($class);
	my @LibraryConfigurations = $ConfigParser->ReadLibraries();

	my $ii = 0;
	foreach (@LibraryConfigurations){
		$ii++;
		$log->debug( "*** SBDir2Lib::LibraryConfiguration[".$ii."].ID          = " . $_->ID             );
		$log->debug( "*** SBDir2Lib::LibraryConfiguration[".$ii."].DisplayName = " . $_->DisplayName    );
		
		$log->debug( "*** SBDir2Lib::LibraryConfiguration[".$ii."].FullID = "      . GetQualifiedID($_) );
		$log->debug( "*** SBDir2Lib::LibraryConfiguration[".$ii."].StringToken = " . GetStringToken($_) );
	}

	# Define some virtual libraries.
	# - id:        the library's ID. Use something specific to your plugin to prevent dupes.
	# - name:      the user facing name, shown in menus and settings
	# - sql:       a SQL statement which creates the records in library_track
	# - scannerCB: a sub ref to some code creating the records in library_track. Use scannerCB
	#              if your library logic is a bit more complex than a simple SQL statement.
	foreach( {
		id => 'Dir2Lib_All',
		name => 'All tracks',
		# %s is being replaced with the library's ID
		sql => qq{
			INSERT OR IGNORE INTO library_track (library, track)
				SELECT '%s', tracks.id FROM tracks
		}
	},{
		id => 'Dir2Lib_AudioBooks',
		name => 'Audio Books',
		# %s is being replaced with the library's ID
		sql => qq{
			INSERT OR IGNORE INTO library_track (library, track)
				SELECT '%s', tracks.id 
				FROM tracks 
				WHERE tracks.url LIKE '%%Audio Books%%'
		}
	},{
		id => 'Dir2Lib_Kids',
		name => 'Kids',
		sql => qq{
			INSERT OR IGNORE INTO library_track (library, track)
				SELECT '%s', tracks.id 
				FROM tracks 
				WHERE tracks.url LIKE '%%/Kids/%%'
		}
	},{
		id => 'Dir2Lib_MyLove',
		name => 'MyLove',
		sql => qq{
			INSERT OR IGNORE INTO library_track (library, track)
				SELECT '%s', tracks.id 
				FROM tracks 
				WHERE tracks.titlesearch LIKE '%%LOVE%%'
		}
	}) {
	    $log->debug( "*** SBDir2Lib: registerLibrary : " .$_->{sql} );
		Slim::Music::VirtualLibraries->registerLibrary($_);
	}
	
	refreshLibraries();
	
	Slim::Utils::Strings::storeExtraStrings([{
		strings => { EN => 'Kids Artists'},
		token   => uc('DEMO_ARTISTS'),
	}]);
	
	Slim::Utils::Strings::storeExtraStrings([{
		strings => { EN => 'Kids Alben'},
		token   => uc('DEMO_ALBUMS'),
	}]);
	
	my @menus = ( {
		name => 'DEMO_ARTISTS',
		icon => 'html/images/artists.png',
		feed => \&Slim::Menu::BrowseLibrary::_artists,
		id   => 'artistsWithKids',
		weight => 15,
	},{
		name => 'DEMO_ALBUMS',
		icon => 'html/images/albums.png',
		feed => \&Slim::Menu::BrowseLibrary::_albums,
		id   => 'albumsWithKids',
		weight => 25,
	} );
	
	# this demonstrates how to make use of libraries without switching 
	# the full browsing experience to one particular library
	# create some custom menu items based on one library
	foreach (@menus) {
		Slim::Menu::BrowseLibrary->registerNode({
			type         => 'link',
			name         => $_->{name},
			params       => { library_id => Slim::Music::VirtualLibraries->getRealId('Dir2Lib_Kids') },
			feed         => $_->{feed},
			icon         => $_->{icon},
			jiveIcon     => $_->{icon},
			homeMenuText => $_->{name},
			condition    => \&Slim::Menu::BrowseLibrary::isEnabledNode,
			id           => $_->{id},
			weight       => $_->{weight},
			cache        => 1,
		});
	}
	
	$class->SUPER::initPlugin(@_);
}


#----------------------------------------------------------------------
sub getCurrentDBH {
	return Slim::Schema->storage->dbh();
}


#----------------------------------------------------------------------
sub refreshLibraries {
	$log->info("SBDir2Lib:Synchronizing libraries data, please wait...\n");
	my $dbh = getCurrentDBH();

	if(defined(Slim::Music::VirtualLibraries->getRealId('Dir2Lib_Kids'))) {
		my $id = Slim::Music::VirtualLibraries->getRealId('Dir2Lib_Kids');
		
		$log->info("SBDir2Lib: Deleting entries for ".Slim::Music::VirtualLibraries->getNameForId($id));
		
		my $delete_sth = $dbh->prepare_cached('DELETE FROM library_track WHERE library = ?');
	    $delete_sth->execute($id);
	    $delete_sth->finish();
		
		$log->info("SBDir2Lib: Creating entries for ".Slim::Music::VirtualLibraries->getNameForId($id));
		$log->debug("SBDir2Lib: Using: ".Slim::Music::VirtualLibraries::getLibraries()->{$id}->{sql});
	    $dbh->do(sprintf(Slim::Music::VirtualLibraries::getLibraries()->{$id}->{sql},$id));
	}
	
	$log->info("SBDir2Lib:Synchronization finished\n");
}


#----------------------------------------------------------------------
sub GetConfigParser {
	my $classPlugin = shift;
	
	if( !defined($ConfigParser) ){
		$ConfigParser = Plugins::SBDir2Lib::ConfigParser->new($classPlugin);
	}
	return $ConfigParser;
}


#----------------------------------------------------------------------
sub GetQualifiedID {
	my $LibraryConfiguration = shift;

	my $FullID = 'SBDir2Lib_' . $LibraryConfiguration->ID;

	return $FullID;
}


#----------------------------------------------------------------------
sub GetStringToken {
	my $LibraryConfiguration = shift;

	my $StringToken = 'SBDIR2LIB_' . $LibraryConfiguration->ID . "_DISPLAYSTRING";

	return $StringToken;
}



1;